package com.news.dao;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;

import java.util.List;

/**
 * Created by totem on 2014/10/31.
 */
public class BaseDao {
    @Autowired
    protected HibernateTemplate hibernateTemplate;

    @Autowired
    protected SessionFactory sessionFactory;

    public <T> T getById(Class<T> clazz, long id) {
        T object = hibernateTemplate.get(clazz, id);
        return object;

    }


    protected List findByPageBean(final int offset, final int pageSize,
                                  final String hql, String queryKey, long lastId) {

        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(hql);
        query.setMaxResults(pageSize);
        query.setFirstResult(offset);
        int i = 0;

        if (queryKey != null) {
            query.setString(i++, queryKey);
        }
        if (lastId > 0) {
            query.setLong(i++, lastId);
        }
        List list = query.list();
        return list;
    }

    protected List queryForAppPage(int pageSize, long lastId, String hql, String queryKey) {

        return findByPageBean(0, pageSize, hql, queryKey, lastId);

    }

    protected List queryForAppPage(int pageSize, long lastId, String hql) {

        return findByPageBean(0, pageSize, hql, null, lastId);

    }

    protected List queryForAddOneData(int pageSize, int pageNumber, String hql, long userId) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(hql);
        query.setMaxResults(pageSize + 1);
        query.setFirstResult(pageSize * (pageNumber - 1));
        query.setLong(0, userId);
        List list = query.list();
        return list;
    }

    protected List queryForAddOneData(int pageSize, int pageNumber, String hql) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(hql);
        query.setMaxResults(pageSize + 1);
        query.setFirstResult(pageSize * (pageNumber - 1));

        List list = query.list();
        return list;
    }

    public void evict(Object object) {
        Session session = sessionFactory.getCurrentSession();
        session.evict(object);
    }

    public void saveOrUpdate(Object object) {
        hibernateTemplate.saveOrUpdate(object);
    }

    public long count(Class cla) {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(cla);
        criteria.setProjection(Projections.rowCount());
        List results = criteria.list();
        long totalRows = Long.parseLong(results.get(0).toString());
        return totalRows;
    }

    public long countLike(Class cla, Object value, String... properties) {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(cla);
        org.hibernate.criterion.Criterion[] criterias = new org.hibernate.criterion.Criterion[properties.length];
        for (int i = 0; i < properties.length; i++) {

            org.hibernate.criterion.Criterion newCriteria = Restrictions.ilike(properties[i], value);
            criterias[i] = newCriteria;
        }
        criteria.add(Restrictions.or(criterias));
        criteria.setProjection(Projections.rowCount());
        long totalRows = Long.parseLong(criteria.uniqueResult().toString());

        return totalRows;
    }

    public void batchDelete(List list) {
        hibernateTemplate.deleteAll(list);
    }

    public void batchSaveOrUpdate(List list) {
        for (Object object : list) {
            hibernateTemplate.saveOrUpdate(object);
        }
    }


    //public List queryByKey(String tableName,Class cla,String value ,int startIndex,int pageSize,String ... propertys){
//    Session session = sessionFactory.getCurrentSession();
//    String sql = "";
//    for (String property : propertys){
//        sql +="(select * from "+tableName+" where " + property +" like ?)  union  ";
//       }
//    sql = sql.substring(0,sql.lastIndexOf("union"));
//    Query query = session.createSQLQuery(sql).addEntity(cla);
//    for (int i=0;i<propertys.length;i++){
//        query.setParameter(i,value);
//    }
//    query.setFirstResult(startIndex-1);
//    query.setMaxResults(pageSize);
//    List list = query.list();
//    return  list;
//}
    public long countByEqual(Class cla, Object value, String key) {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(cla);


        criteria.add(Restrictions.eq(key, value));
        criteria.setProjection(Projections.rowCount());
        long totalRows = (Long) criteria.uniqueResult();

        return totalRows;
    }

    public void delete(Object object) {
        hibernateTemplate.delete(object);
    }
}
